/* eslint-disable vue/require-default-prop */
<template :visible.sync="visibility" style="overflow-y: scroll; overflow-x: hidden; height: 100%">
  <div v-if="groupList">
    <el-card
      style="margin-top: 10px"
      v-for="(group, index) in groupList"
      id="el-test"
      :key="group.recordTemplateGroupId"
    >
      <div slot="header" class="clearfix">
        <span>{{ group.recordTemplateGroupName }}</span>
      </div>

      <div v-if="group.itemList" class="record-template">
        <div v-if="!currentStatus">
          <el-row
            v-for="item in group.itemList"
            :key="item.recordTemplateItemId"
            class="recordRow"
          >
            <el-col :span="1">
              {{ item.sequence }}
            </el-col>
            <el-col
              :span="23"
              v-html="renderHtml(item.content, item.recordTemplateItemId)"
            />
          </el-row>
        </div>
        <el-table
          v-if="currentStatus"
          key="recordTemplateItemId"
          :data="group.itemList"
          :show-header="false"
          highlight-current-row
        >
          <el-table-column label="A">
            <template slot-scope="scope">
              <div
                style="text-align: left"
                v-html="
                  renderHtml(scope.row.content, scope.row.recordTemplateItemId)
                "
              />
            </template>
          </el-table-column>
          <el-table-column label="B">
            <template slot-scope="scope" fixed="left">
              <el-checkbox
                v-model="scope.row.checkFlag"
                @change="checkboxChange(scope.row, scope.$index)"
                >确认</el-checkbox
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  parseToHtml,
  getElementById
} from '@/views/manufacture/template/scripts/base'
import { parseTextToHtml } from '@/views/manufacture/template/scripts/text'
import {
  getOptionData,
  parseOptionToHtml
} from '@/views/manufacture/template/scripts/option'
import {
  getFillData,
  parseFillToHtml
} from '@/views/manufacture/template/scripts/fill'
import {
  getTableData,
  parseTableToHtml
} from '@/views/manufacture/template/scripts/table'
import UglyMap from '@/utils/uglyMap'
import { isArrEqual } from '@/utils/common.js'
import { saveCheckEquipment } from '@/api/mes/manufactureTask.js'

export default {
  props: {
    visible: {
      required: true,
      type: Boolean
    },
    currentTask: {
      type: Object,
      default: null
    },
    currentRow: {
      type: Object,
      default: null
    },
    updatedData: {
      type: Function,
      default: function name(params) {}
    },
    currentStatus: {
      type: Boolean,
      required: false
    },
    currentType: {
      type: String,
      required: false,
      default: 'manufacture'
    }
  },
  data() {
    return {
      loading: false,
      groupList: null,
      recordMap: null,
      tempObjArray: null,
      temp: {},
      isCheckboxChange: false,
      timer: null,
      tempCurrentTask: null
    }
  },
  computed: {
    visibility: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible(value) {
      if (value) {
        const ID = this.currentType + 'Id'
        const CODE = this.currentType + 'Code'
        this.tempCurrentTask = {
          taskCode: this.currentTask[ID],
          taskId: this.currentTask[CODE],
          orderType: this.currentTask.orderType
        }
      }
    },
    currentRow(data) {
      this.clearTimer()
      this.sendTimer()
      this.loadIsTemplate(data)
    }
  },
  mounted() {
    window.handleOptionClick = (id) => {
      this.handleOptionClick(id)
    }
  },
  beforeDestroy() {
    this.clearTimer()
  },
  methods: {
    sendTimer() {
      this.timer = setInterval(() => {
        let itemObjArray = []
        itemObjArray = this.createDomData(this.groupList)
        const arr1 = this.tempObjArray || []
        let is = false
        this.tempObjArray = itemObjArray
        is = isArrEqual(arr1, itemObjArray)
        if (!is && !this.currentStatus) {
          this.handleCommit()
        }
      }, 5000)
    },
    clearTimer() {
      clearInterval(this.timer)
      this.timer = null
    },
    handleOptionClick(id) {
      if (document.getElementById(id).checked) {
        // document.getElementById(id).checked = false
      } else {
        document.getElementById(id).checked = true
      }
    },
    renderHtml(template, recordTemplateItemId) {
      const record = this.recordMap.get(recordTemplateItemId)
      const html = parseToHtml(
        template,
        record,
        [parseTextToHtml, parseOptionToHtml, parseFillToHtml, parseTableToHtml],
        recordTemplateItemId,
        this.currentStatus
      )
      return html
    },
    handleBeforeClose(done) {
      this.$confirm('是否保存表单数据?', '提示', {
        confirmButtonText: '保存',
        cancelButtonText: '不保存',
        type: 'warning'
      })
        .then(() => {
          //
        })
        .catch(() => {
          //
        })
        .finally(() => {
          done()
        })
    },
    handleClose() {
      this.handleBeforeClose(() => {
        this.visibility = false
      })
    },
    createDomData(data) {
      const itemObjArray = []
      if (this.groupList) {
        let itemObj = null
        let segmentValue = null
        let segmentValueArray = null
        let elementId = null
        data.forEach((group) => {
          if (group.itemList) {
            group.itemList.forEach((item) => {
              itemObj = {
                [this.currentType + 'Id']: this.tempCurrentTask.taskId,
                [this.currentType + 'Code']: this.tempCurrentTask.taskCode,
                recordTemplateItemId: item.recordTemplateItemId,
                content: null,
                version: item.version
              }
              itemObjArray.push(itemObj)
              segmentValueArray = []
              for (let k = 0; k < item.segmentCount; k++) {
                elementId = item.recordTemplateItemId + '-' + k
                let element = getElementById(elementId)
                if (element) {
                  // fill input
                  segmentValue = {
                    index: k,
                    value: getFillData(elementId)
                  }
                  segmentValueArray.push(segmentValue)
                } else {
                  element = getElementById(elementId + '-' + 0)
                  if (element != null) {
                    // option input
                    segmentValue = {
                      index: k,
                      value: getOptionData(elementId)
                    }
                    segmentValueArray.push(segmentValue)
                  } else {
                    element = getElementById(elementId + '-' + 0 + '-' + 0)
                    if (element != null) {
                      // table input
                      segmentValue = {
                        index: k,
                        value: getTableData(elementId)
                      }
                      segmentValueArray.push(segmentValue)
                    } else {
                      // text or image readonly, so do nothing.
                    }
                  }
                }
              }
              itemObj.content = JSON.stringify(segmentValueArray)
            })
          }
        })
        return itemObjArray
      }
    },
    handleCommit() {
      let itemObjArray = []
      itemObjArray = this.createDomData(this.groupList)
      const newData = {
        recordList: itemObjArray,
        [this.currentType + 'Id']: this.tempCurrentTask.taskId,
        [this.currentType + 'Code']: this.tempCurrentTask.taskCode,
        recordTemplateId: this.currentRow.recordTemplateId
      }
      if (itemObjArray && itemObjArray.length !== 0) {
        this.$emit('update-data', newData)
      }
      this.visibility = false
    },
    loadIsTemplate(row) {
      this.groupList = []
      let data = row.recordTemplateGroupList || []
      const data2 = row.recordList || []
      this.recordMap = new UglyMap()
      if (data2 && data2.length > 0) {
        data2.forEach((e) => {
          this.recordMap.put(e.recordTemplateItemId, JSON.parse(e.content))
        })
      }
      this.groupList = Array.from(data)
      this.$forceUpdate()
    },
    checkboxChange(row, index) {
      this.currentRow.recordList[index].checkFlag = true
      const pushData = {
        [this.currentType + 'Code']: this.tempCurrentTask.taskCode,
        [this.currentType + 'Id']: this.tempCurrentTask.taskId,
        recordList: this.currentRow.recordList
      }
      saveCheckEquipment(pushData).then((res) => {
        this.$emit('update-data', this.tempCurrentTask)
      })
    },
    inCheckFlag(arr1, arr2) {
      arr1.forEach((e, index) => {
        if (arr2[index] && e.itemList.length > 0) {
          e.itemList.forEach((e2, index2) => {
            if (arr2.length <= index2) {
              return
            } else {
              e2.checkFlag = arr2[index2].checkFlag || false
            }
          })
        } else {
          return
        }
      })
      return arr1
    }
  }
}
</script>

<style lang="scss">
</style>
